package com.example.petstore.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthorityInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String backUrl = request.getServletPath().toString();
		String sessionName = "adminUser";
		String currentUser = (String)request.getSession(true).getAttribute(sessionName);
		if(currentUser != null && currentUser.equals("admin")) {
			return true;
		}
		response.sendRedirect(request.getContextPath() + "/admin/toLogin?backUrl=" + backUrl);
		return false;
	}
}
